package com.yonyou.iuap.jxzy.controller;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

import net.sf.json.JSONObject;

import org.apache.commons.lang.WordUtils;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.collections.MapUtils;

import com.alibaba.fastjson.JSONArray;
import com.yonyou.iuap.base.web.BaseController;
import com.yonyou.iuap.mvc.constants.RequestStatusEnum;
import com.yonyou.iuap.jxzy.entity.MonitorSample;
import com.yonyou.iuap.jxzy.service.MonitorSampleService;
import com.yonyou.iuap.mvc.annotation.FrontModelExchange;
import com.yonyou.iuap.mvc.type.SearchParams;
import com.yonyou.iuap.mvc.type.JsonResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;

import org.springframework.util.StringUtils;

import com.yonyou.iuap.common.utils.ExcelExportImportor;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * 说明：监控抽样 基础Controller——提供数据增、删、改、查、导入导出等rest接口
 * 
 * @date 2019-5-13 15:51:06
 */
@Controller
@RequestMapping(value="/jx_monitorSample")
public class MonitorSampleController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(MonitorSampleController.class);

    private MonitorSampleService monitorSampleService;

    @Autowired
    public void setMonitorSampleService(MonitorSampleService monitorSampleService) {
        this.monitorSampleService = monitorSampleService;
    }


    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(PageRequest pageRequest, SearchParams searchParams) {
    	Map<String, Object> searchMap = searchParams.getSearchMap();
    	if(searchMap.get("pk_material")!=null){
    		String string = searchMap.get("pk_material").toString();
    		searchMap.put("pk_material", string.replace(",", "','"));
    	}
        Page<MonitorSample> page = this.monitorSampleService.selectAllByPage(pageRequest, searchParams);
        for(MonitorSample monitorSample : page){
        	String imgurl=monitorSample.getPath();
        	String samplearray=monitorSample.getSampleArray();
        	String purchasOrg=monitorSample.getName();
        	monitorSample.setPurchasOrg(purchasOrg);
        	
        	//初始化抽样位置
        	/*String rowNo=monitorSample.getRowNo();//排数
        	String columnNo=monitorSample.getColumnNo();
        	String samplingLocation=rowNo+"排"+columnNo+"列".toString();
        	monitorSample.setSamplingLocation(samplingLocation);*/
        	
        	//String[] imgUrls=url.split(",");
        	if(imgurl!=null){
				String[] imgurls=imgurl.split(",");
				monitorSample.setSampleAreaPhoto(imgurls);//前端图片展示
			}
        	if(samplearray!=null){
        		String[] pumpingPosition=samplearray.split(",");
				monitorSample.setPumpingPosition(pumpingPosition);//前端图片展示
        	}
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", page);
        return this.buildMapSuccess(map);
    }

    @RequestMapping(value = "/get")
    @ResponseBody
    public Object get(PageRequest pageRequest, SearchParams searchParams) {
        String id = MapUtils.getString(searchParams.getSearchMap(), "id");
        if (id==null){
            return this.buildSuccess();//前端约定传空id则拿到空对象
        }
        if(StrUtil.isBlank(id)) {
            return this.buildError("msg", "主键id参数为空!", RequestStatusEnum.FAIL_FIELD);
        }else {
            MonitorSample entity = this.monitorSampleService.findById(id);
            return this.buildSuccess(entity);
        }
    }
    
    
    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(@RequestBody MonitorSample entity) {
        JsonResponse jsonResp;
        try {
            this.monitorSampleService.save(entity);
            jsonResp = this.buildSuccess(entity);
        }catch(Exception exp) {
            jsonResp = this.buildError("msg", exp.getMessage(), RequestStatusEnum.FAIL_FIELD);
        }
        return jsonResp;
    }

    @RequestMapping(value = "/saveBatch")
    @ResponseBody
    public Object saveBatch(@RequestBody List<MonitorSample> listData) {
        this.monitorSampleService.saveBatch(listData);
        return this.buildSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestBody MonitorSample entity, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.monitorSampleService.delete(entity);
        return super.buildSuccess();
    }

    @RequestMapping(value = "/deleteBatch")
    @ResponseBody
    public Object deleteBatch(@RequestBody List<MonitorSample> listData, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.monitorSampleService.deleteBatch(listData);
        return super.buildSuccess();
    }


    @RequestMapping(value = "/excelTemplateDownload", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Map<String, String> excelTemplateDownload(HttpServletRequest request,
            HttpServletResponse response){
        Map<String, String> result = new HashMap<String, String>();

        try {
            ExcelExportImportor.downloadExcelTemplate(response, getImportHeadInfo(), "监控抽样", "监控抽样模板");
            result.put("status", "success");
            result.put("msg", "Excel模版下载成功");
        } catch (Exception e) {
            logger.error("Excel模版下载失败", e);
            result.put("status", "failed");
            result.put("msg", "Excel模版下载失败");
        }
        return result;
    }

    @RequestMapping(value = "/toImportExcel", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> importExcel(HttpServletRequest request){
        Map<String, String> result = new HashMap<String, String>();
        try {

            List<MonitorSample> list = new ArrayList<MonitorSample>();
            CommonsMultipartResolver resolver = new CommonsMultipartResolver();
            if(resolver.isMultipart(request)){
                 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                 int size = multipartRequest.getMultiFileMap().size();
                 MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
                 if(multiValueMap !=null && size > 0){
                    for(MultiValueMap.Entry<String, List<MultipartFile>> me : multiValueMap.entrySet()){
                        List<MultipartFile> multipartFile = me.getValue();
                        for(MultipartFile mult : multipartFile){
                            String multName =  mult.getOriginalFilename().toString();
                            String multTypeName = multName.substring(multName.lastIndexOf(".")+1, multName.length());
                            if((multTypeName != "xlsx" && !"xlsx".equals(multTypeName)) && (multTypeName != "xls" && !"xls".equals(multTypeName))){
                                throw new Exception("导入数据格式异常！");
                            }
                            list = ExcelExportImportor.loadExcel(mult.getInputStream(), getImportHeadInfo(), MonitorSample.class);
                            if(list==null || list.size()== 0){
                                throw new Exception("导入数据异常！");
                            }
                        }
                    }
                 }
            }
            monitorSampleService.saveBatch(list);
            result.put("status", "success");
            result.put("msg", "Excel导入成功");
        } catch (Exception e) {
            logger.error("Excel导入失败", e);
            result.put("status", "failed");
            result.put("msg", e.getMessage()!=null?e.getMessage():"Excel导入失败");
        }
        return result;
    }

    @RequestMapping(value = "/toExportExcel",method = RequestMethod.POST)
    @ResponseBody
    public Object exportExcel(PageRequest pageRequest,
                        @FrontModelExchange(modelType = MonitorSample.class) SearchParams searchParams,HttpServletResponse response,@RequestBody List<MonitorSample> dataList){

       Map<String, String> result = new HashMap<String, String>();
       try {
          List idsList = new ArrayList();
          for (MonitorSample entity : dataList) {
             idsList.add(entity.getId());
          }
          List list = monitorSampleService.selectListByExcelData(idsList);
          ExcelExportImportor.writeExcel(response, list, getExportHeadInfo(), "监控抽样", "监控抽样");
          result.put("status", "success");
          result.put("msg", "信息导出成功");
          result.put("fileName", "监控抽样");
       } catch (Exception e) {
          logger.error("Excel下载失败", e);
          result.put("status", "failed");
          result.put("msg", "Excel下载失败");
       }
       return result;
    }

    @RequestMapping(value = "/toExportExcelAll",method = RequestMethod.GET)
    @ResponseBody
    public Object exportExcelAll(PageRequest pageRequest,
                        @FrontModelExchange(modelType = MonitorSample.class) SearchParams searchParams,HttpServletResponse response){

       Map<String, String> result = new HashMap<String, String>();
       try {
          Page<MonitorSample> page = monitorSampleService.selectAllByPage(pageRequest, searchParams);
          List list = page.getContent();
          if(list == null || list.size()==0){
              throw new Exception("没有导出数据！");
          }
          ExcelExportImportor.writeExcel(response, list, getExportHeadInfo(), "监控抽样", "监控抽样");
          result.put("status", "success");
          result.put("msg", "信息导出成功");
       } catch (Exception e) {
          logger.error("Excel下载失败", e);
          result.put("status", "failed");
          result.put("msg", "Excel下载失败");
       }
       return result;
    }

    private Map<String, String> getExportHeadInfo() {
        String values = "{'pk_monitorSample':'主键',}";
        return getMapInfo(values);
    }

    private Map<String, String> getImportHeadInfo() {
        String values = "{'pk_monitorSample':'主键',}";
        return getMapInfo(values);
    }

    private Map<String, String> getMapInfo(String values){
        String values_new = values.substring(0, values.length()-1);
        if(values_new.endsWith(",")){
                values = values_new.substring(0, values_new.length()-1)+"}";
        }
        Map<String, String> headInfo = null;
        //if (headInfo == null) {
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(values);
        headInfo = (Map<String, String>) json;
        //}
        return headInfo;
    }
    
    /**
     * 核查货物总数 列 排 层 总包数
     * @param monitorSample
     * @return
     */
    @RequestMapping(value = "/verificationCargo",method = RequestMethod.POST)//
    @ResponseBody
    public Object checkGoodsNum(@RequestBody MonitorSample monitorSample){
    	
    	JSONObject jsonObject=new JSONObject();
    	try {
    		String id=monitorSample.getPk_poundbill();
    		String columnNo=monitorSample.getColumnNo();
        	String rowNo=monitorSample.getRowNo();
        	String layerNo=monitorSample.getLayerNo();
        	String totalPackageNo=monitorSample.getTotalPackageNo();
        	String updateNUm=monitorSampleService.updateParamByPoundNo(id,columnNo,rowNo,layerNo,totalPackageNo);
        	return this.buildSuccess(updateNUm);
		} catch (Exception e) {
			jsonObject.put("message", "核查货物总数异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
    }
    
    /**
     * 加抽样本
     * @param monitorSample
     * @return
     */
    @RequestMapping(value = "/resampling",method = RequestMethod.POST)//verificationCargo
    @ResponseBody
    public Object sampleToAdd(@RequestBody MonitorSample monitorSample){
    	JSONObject jsonObject=new JSONObject();
    	try {
        	String updateNUm=monitorSampleService.sampleToAdd(monitorSample);
        	return this.buildSuccess(updateNUm);
		} catch (Exception e) {
			jsonObject.put("message", "加抽异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
    }
    
    /**
     * 不加抽样本
     * @param monitorSample
     * @return
     */
    @RequestMapping(value = "/not-resampling",method = RequestMethod.POST)//verificationCargo
    @ResponseBody
    public Object notSampleToAdd(@RequestBody MonitorSample monitorSample){
    	JSONObject jsonObject=new JSONObject();
    	try {
        	String result=monitorSampleService.notSampleToAdd(monitorSample);
        	return this.buildSuccess(result);
		} catch (Exception e) {
			jsonObject.put("message", "不加抽异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
    }
    
    /**
     * 审核通过 根据主键更改状态
     * @param monitorSample
     * @return
     */
    @RequestMapping(value = "/confirmVerify",method = RequestMethod.POST)
    @ResponseBody
    public Object auditPass(@RequestBody MonitorSample monitorSample){
    	
    	JSONObject jsonObject=new JSONObject();
    	try {
        	Integer updateNUm=monitorSampleService.auditPass(monitorSample);
        	return this.buildSuccess(updateNUm);
		} catch (Exception e) {
			jsonObject.put("message", "审核异常："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
    }
    
    /**
     * 是否人工检测 根据主键更改状态
     * @param monitorSample
     * @return
     */
    @RequestMapping(value = "/manual-detection",method = RequestMethod.POST)
    @ResponseBody
    public Object changeStatus(@RequestBody MonitorSample monitorSample){
    	
    	JSONObject jsonObject=new JSONObject();
    	String pk_poundbill=monitorSample.getPk_poundbill();
    	String  humanVerifyFlag=monitorSample.getHumanVerifyFlag();
    	try {
        	Integer updateNUm=monitorSampleService.changeStatus(pk_poundbill,humanVerifyFlag);
        	return this.buildSuccess(updateNUm);
		} catch (Exception e) {
			jsonObject.put("message", "人工检测："+e.getMessage());
			jsonObject.put("success", "error");
		}
		 return jsonObject.toString();
    }
    
    @RequestMapping(value = "/ces")
    @ResponseBody
    public Object queryBypk(@RequestParam String pk) {
    	List<MonitorSample> queryBypk = this.monitorSampleService.queryBypk(pk);
    	if(queryBypk.size()>0 && queryBypk.get(0)!=null){
    		String a=null;
    	}
        return null;
    }



}